package com.baizhi.controller;


import com.alibaba.druid.util.StringUtils;
import com.baizhi.annotations.RequiredToken;
import com.baizhi.dto.UserDTO;
import com.baizhi.dto.UserDTO;
import com.baizhi.dto.VideoDTO;
import com.baizhi.entity.User;
import com.baizhi.entity.Video;
import com.baizhi.feign.VideosClient;
import com.baizhi.service.UserService;
import com.baizhi.utils.JSONUtils;
import com.baizhi.utils.OSSUtils;
import com.baizhi.vo.PhoneCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author 2107class
 * @since 2021-12-17
 */
@RestController
@RequestMapping
public class UserController implements Serializable{

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private VideosClient videosClient;

    @PostMapping("/tokens")
    public Map<String,Object> Login(HttpServletRequest request,@RequestBody PhoneCode phoneCode){
        System.out.println(request);
        System.out.println(phoneCode);
        Map<String,Object> login = userService.login(request,phoneCode);
        return login;
    }

    /*@GetMapping("/user")
    public User query(String token){
        User user = userService.queryLogin(token);
        return user;
    }
*/
    @GetMapping("user")
    @RequiredToken
    public Map<String,Object> user(HttpServletRequest request) throws JsonProcessingException {
        User user = (User) request.getAttribute("user");
//        log.info("获取的用户信息为: {}", new ObjectMapper().writeValueAsString(user));

        Map<String,Object> map = new HashMap<>();
        map.put("avatar",user.getAvatar());
        map.put("name",user.getName());
        map.put("intro",user.getIntro());
        map.put("phone",user.getPhone());
//        if( user.getPhoneLinked() != null && user.getPhoneLinked() == 1 ){
            map.put("phone_linked",true);
//        }else{
//            map.put("phone_linked",false);
//        }

        if( user.getWechatLinked() != null && user.getWechatLinked() == 1 ){
            map.put("wechat_linked",true);
        }else{
            map.put("wechat_linked",false);
        }
        return map;
    }


    @GetMapping("/users/{user_id}")
    public User queryOne(@PathVariable("user_id") Integer id){
        User user = userService.queryOne(id);
        return user;
    }

    @DeleteMapping("/token")
    public void loginOut(String token){
        redisTemplate.delete(token);
    }

    /*@PatchMapping("/user")
    public User update(@RequestBody User user,String token){
        User user1 = (User)redisTemplate.opsForValue().get(token);
        user.setId(user1.getId());
        userService.update(user);
        return user;
    }*/



    //用户信息
    @PatchMapping("user")
    @RequiredToken
    public Map<String, Object> user(@RequestBody UserDTO userDTO, HttpServletRequest request) {
        //1.获取token信息
        String token = (String) request.getAttribute("token");
        //2.获取原始用户信息
        User userOld = (User) request.getAttribute("user");


        //3.是否修改手机号
        if (!StringUtils.isEmpty(userDTO.getPhone())) {
            String msgKey = userDTO.getPhone();
            if (!Boolean.TRUE.equals(stringRedisTemplate.hasKey(msgKey))) throw new RuntimeException("提示:验证码已过期!");
            String redisCaptcha = (String) redisTemplate.opsForValue().get(msgKey);
            /*System.out.println(redisCaptcha);
            System.out.println(userDTO.getCaptcha());*/
            if (!StringUtils.equals(redisCaptcha, userDTO.getCaptcha())) throw new RuntimeException("提示:验证码输入错误!");
            userOld.setPhone(userDTO.getPhone());//更新之后手机号
        }

        //4.修改用户名 简介
        if (!StringUtils.isEmpty(userDTO.getName())) userOld.setName(userDTO.getName());
        if (!StringUtils.isEmpty(userDTO.getIntro())) userOld.setIntro(userDTO.getIntro());

        //6.更新用户信息
        userService.update(userOld);

        //6.更新redis中原始用户信息
        redisTemplate.opsForValue().set(token, userOld, 7, TimeUnit.DAYS);
        Map<String,Object> result = new HashMap<>();
        result.put("avatar", userOld.getAvatar());
        result.put("name", userOld.getName());
        result.put("intro", userOld.getIntro());
        result.put("phone", userOld.getPhone());
        result.put("phone_linked", true);
        result.put("wechat_linked", false);
        return result;
    }



    /**
     * 用户发布视频
     */
    @PostMapping("/user/videos")
    //MultipartFile file:用来接收上传视频信息
    //使用video对象接收 视频标题  视频简介  video{title,intro}
    //category_id 代表当前视频分类id
    //request:    当前请求上下文中存在用户信息
    @RequiredToken
    public VideoDTO publishVideos(MultipartFile file, Video video, Integer category_id, HttpServletRequest request) throws IOException {

        //1.获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        log.info("接收文件名称: {}", originalFilename);
        log.info("接收到视频信息: " + new ObjectMapper().writeValueAsString(video));
        log.info("类别id: {}", category_id);
        log.info("文件大小为: {}", file.getSize());

        //2.获取文件后缀 mp4 avi ....
        String ext = FilenameUtils.getExtension(originalFilename);

        //3.生成uuid
        String uuidFileName = UUID.randomUUID().toString().replace("-", "");

        //4.生成uuid文件名名称
        String newFileName = uuidFileName + "." + ext;

        //5.上传阿里云oss 返回文件在oss地址
        String url = OSSUtils.upload(file.getInputStream(), "videos", newFileName);
        log.info("上传成功返回的地址: {}", url);

        //阿里云oss截取视频中某一帧作为封面
        String cover = url + "?x-oss-process=video/snapshot,t_30000,f_jpg,w_0,h_0,m_fast,ar_auto";
        log.info("阿里云oss根据url截取视频封面: {}", cover);

        //6.设置视频信息
        video.setCover(cover);//设置视频封面
        video.setLink(url);//设置视频地址
        video.setCategoryId(category_id);//设置类别id

        //7.获取用户信息
        User user = (User) request.getAttribute("user");
        video.setUid(user.getId());//设置发布用户id

        //8.调用视频服务
        VideoDTO videoResult = videosClient.publish(video);
        log.info("视频发布成功之后返回的视频信息: {}", JSONUtils.writeValueAsString(videoResult));

       /* //9.生成动态
        Feed feed = new Feed();
        feed.setType("video");//视频类型
        feed.setUserId(video.getUid());
        feed.setVideoId(videoResult.getId());
        feed.setContent(videoResult.getTitle());//视频标题作为动态内容
        feedService.save(feed);
        log.info("动态发布成功,当前动态信息: {}", JSONUtils.writeValueAsString(feed));
*/
        return videoResult;
    }




}

